package crudfx.data;
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.*;
import crudfx.util.*;
/**
 * @profile desktop
 * @author Sergey Surikov
 */
public class FileProperties extends StreamProperties{
    public var path:String on replace oldFile=newFile{
        try{
            stream=new FileInputStream(newFile);
        }catch(x){
            //
        }
    }
    
    function getElement(document:Document,branch:DataTree):Node{
        //println(branch.name);
        var node:Node;
        if(branch.name==""){
            node=document.createTextNode(branch.gather());
        }else{
            try {
                node=document.createElement("badTagName");
                node=document.createElement(branch.name);
            } catch (t) {
                //t.printStackTrace()
                ConsoleIO.error(this,t);
            }
            if(sizeof branch.children > 0) {
                for(b:DataTree in branch.children) {
                    node.appendChild(getElement(document,b));
                }
            if(sizeof branch.attributes > 0) {
                for(a:DataTree in branch.attributes) {
                    var ta:Attr=document.createAttribute(a.name);
                    ta.setValue(a.gather());
                    node.getAttributes().setNamedItem(ta);
                    }
                }
            }
        }
        return node;
    }
    public function save():Void{
        var factory:DocumentBuilderFactory=DocumentBuilderFactory.newInstance();
        var source:Source;
        var result:Result;
        try{
            if(this.name=="")this.name="properties";
            var builder:DocumentBuilder=factory.newDocumentBuilder();
            var document:Document=builder.newDocument();
            var el:Node=getElement(document,this);
            //println("el");
            //println(el);
            if(el==null){
                ConsoleIO.message(this," is null");                
                }
            document.appendChild(el);
            //println("document");
            //println(document);
            source=new DOMSource(document);
            var file:File=new File(path);
            //println(file);
            result=new StreamResult(//java.lang.System.out);
            file);
            var tf:TransformerFactory=TransformerFactory.newInstance();
            tf.setAttribute("indent-number", new java.lang.Integer(2));
            var transformer:Transformer=tf.newTransformer();
            transformer.setOutputProperty("\{http://xml.apache.org/xslt\}indent-amount","5");
            transformer.setOutputProperty("indent","yes");
            transformer.transform(source, result);
        } catch (e) {
            //e.printStackTrace();
            //println(source);
            //println(result);
            ConsoleIO.error(this,e);
        }
    }
}
